package com.ruoyi.web.controller.initData;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.dao.SysDeptDao;
import com.ruoyi.system.domain.dao.SysUserDao;
import com.ruoyi.system.mapper.OaMapper;
import com.ruoyi.system.mapper.SysDeptDaoMapper;
import com.ruoyi.system.mapper.SysUserDaoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class SysUserDeptInit {

    @Autowired
    private OaMapper oaMapper;
    @Autowired
    private SysUserDaoMapper sysUserDaoMapper;
    @Autowired
    private SysDeptDaoMapper sysDeptDaoMapper;

    /**
     *  初始化 用户部门，绑定用户到具体的部门
     */
    public void bindUser2Dept() {
        List<SysUserDao> list = sysUserDaoMapper.selectList(new QueryWrapper<>());
        if (list != null && list.size() > 0) {
            list.stream().forEach(item -> {
                // userUuid=b96e1852522a46399b914fcd8e798d2c,empId=15d41a949a5e487ca6e9ff37f2f60f1e
                if (StringUtils.isEmpty(item.getOldData())) {
                    return;
                }
                String[] split = item.getOldData().split(",");
                if (split.length > 1) {
                    String userUuid = split[0].split("=")[1];
                    String empId = split[1].split("=")[1];
                    List<Map<String, String>> listData = oaMapper.listDataByCondition("ent_t_humen_root", "emp_id", empId);
                    if (listData != null && listData.size() > 0) {
                        Map<String, String> val = listData.get(0);
                        String entTDepUuid = val.get("ent_t_dep_uuid"); // 旧数据所在部门
                        LambdaQueryWrapper lw = new LambdaQueryWrapper<SysDeptDao>()
                                .likeRight(SysDeptDao::getOldData, String.format("depUuid=%s", entTDepUuid));
                        SysDeptDao sysDept = sysDeptDaoMapper.selectOne(lw);
                        if (sysDept != null) {
                            item.setDeptId(sysDept.getDeptId());
                            sysUserDaoMapper.updateById(item);
                        }
                    }
                }
            });
        }
    }
}
